from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config import settings

# SQLALCHEMY_DATABASE_URL = f"postgresql://{settings.db_user}:{settings.db_password}@{settings.db_host}:{settings.db_port}/{settings.db_name}"
SQLALCHEMY_DATABASE_URL = f"mysql+pymysql://{settings.db_user}:{settings.db_password}@{settings.db_host}:{settings.db_port}/{settings.db_name}"

global_engine = create_engine(SQLALCHEMY_DATABASE_URL)
# 创建会话工厂，用于生成数据库会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=global_engine)

# 定义声明式基类，所有数据库模型类都将继承自该基类
Base = declarative_base()


# 定义一个生成器函数，用于获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()